import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'
import { useIntervalFn } from '@vueuse/shared'
import dayjs from 'dayjs'
export const useLazyData = apiFn => {
  const target = ref(null)
  const list = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        stop()
        // console.log(321)
        apiFn &&
          apiFn().then(date => {
            list.value = date.result
          })
      }
    },
    {
      threshold: 0
    }
  )
  return {
    target,
    list
  }
}
// 🔔 作业：倒计时效果
export const usePayTime = () => {
  const time = ref(0)
  const timeText = ref('')
  const { resume, pause } = useIntervalFn(() => {
    time.value--
    // 格式化后中文时间
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    if (time.value <= 0) {
      time.value = 0
      timeText.value = '已超时'
      pause()
    }
  }, 1000, { immediate: false })
  const start = (number) => {
    // console.log(number)
    if (number === -1) {
      // console.log(2)
      time.value = 0
      timeText.value = '已超时'
      pause()
      return
    }
    time.value = number
    // 格式化后中文时间
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    resume()
  }
  return { time, timeText, start }
}
